﻿using UnityEngine;

namespace Ning.Tools
{
    /// <summary>
    /// Singleton pattern.
    /// </summary>
    public class Singleton<T> : MonoBehaviour where T : Component
    {
        public bool isSetDontDestoryOnLoad = false;   //设置是否不销毁
        bool isInited = false;   //是否初始化过

        protected static T _instance;

        /// <summary>
        /// Singleton design pattern
        /// </summary>
        /// <value>The instance.</value>
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    GameObject obj = new GameObject();
                    _instance = obj.AddComponent<T>();
                }
                return _instance;
            }
        }

        /// <summary>
        /// On awake, we initialize our instance. Make sure to call base.Awake() in override if you need awake.
        /// </summary>
        protected virtual void Awake()
        {
            if (!Application.isPlaying)
            {
                return;
            }

            if (_instance == null)
            {
                //If I am the first instance, make me the Singleton
                _instance = this as T;
                if (isSetDontDestoryOnLoad)
                {
                    DontDestroyOnLoad(transform.gameObject);
                }
                if (!isInited)
                {
                    Init();    //没有初始化过则初始化
                    isInited = true;
                }
            }
            else
            {
                //If a Singleton already exists and you find
                //another reference in scene, destroy it!
                if (this != _instance)
                {
                    Destroy(this.gameObject);
                }
            }
            _instance = this as T;
        }

        protected virtual void Init()
        {
        }
    }
}
